package m1_simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws Exception, TimeoutException {
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.126.129");
        f.setUsername("admin");
        f.setPassword("admin");

        //建立连接
        Connection c = f.newConnection();
        //简历信道
        Channel ch = c.createChannel();
        /**
        //声明队列，如果该队列已经创建过，则不会重复创建
        ch.queueDeclare("task_queue",true,false,false,null);
        */

        //定义名字是logs的交换机，它的类型是fanout
        ch.exchangeDeclare("logs","fanout");

        //自动生成队列名
        //非持久，独占，自动删除
        String queueName = ch.queueDeclare().getQueue();

        //把队列名，绑定到logs交换机，roughtingKey会被忽略，不允许null值
        ch.queueBind(queueName,"logs","");

        System.out.println("等待接受数据");

        /**
        //定义一次只接受一条信息
        //QOS:quality of service 如果设置成1，每次只抓取一条信息
        ch.basicQos(1);
        */

        //收到消息后用来处理消息的回调对象
        DeliverCallback callback = new DeliverCallback(){

            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                String msg = new String(delivery.getBody(),"utf-8");
                System.out.println("收到："+msg);

                /**
                //遍历字符串中的字符，每个点使进程暂停一秒
                for (int i = 0;i < msg.length() ; i++){
                    if (msg.charAt(i)=='.'){
                        try {
                            Thread.sleep(1000);
                        }catch (Exception e ){}
                    }
                }
                */

                System.out.println("处理结束");
               /* //发送回执
                ch.basicAck(delivery.getEnvelope().getDeliveryTag(),false);*/
            }
        };

        //消费者取消时的回调对象
        CancelCallback cancel = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };
        //autoAck设置为false，则需要手动确认发送回执
        ch.basicConsume(queueName,true,callback,cancel);

    }
}
